ENV['RCT_NEW_ARCH_ENABLED'] = '1'
ENV['SODIUM_ENABLED'] = '1'

# Resolve react_native_pods.rb with node to allow for hoisting
require Pod::Executable.execute_command('node', ['-p',
  'require.resolve(
    "react-native/scripts/react_native_pods.rb",
    {paths: [process.argv[1]]},
  )', __dir__]).strip

platform :ios, min_ios_version_supported
prepare_react_native_project!

linkage = ENV['USE_FRAMEWORKS']
if linkage != nil
  Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green
  use_frameworks! :linkage => linkage.to_sym
end

target 'QuickCryptoExample' do
  config = use_native_modules!

  use_react_native!(
    :path => config[:reactNativePath],
    # # An absolute path to your application root.
    :app_path => "#{Pod::Config.instance.installation_root}/..",
  )

  post_install do |installer|
    # https://github.com/facebook/react-native/blob/main/packages/react-native/scripts/react_native_pods.rb#L197-L202
    react_native_post_install(
      installer,
      config[:reactNativePath],
      :mac_catalyst_enabled => false,
      # :ccache_enabled => true
    )

    # https://github.com/mrousavy/nitro/issues/422#issuecomment-2545988256
    installer.pods_project.targets.each do |target|
      target.build_configurations.each do |config|
        config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '16.1'
        config.build_settings['CLANG_CXX_LANGUAGE_STANDARD'] = 'c++20'

        # Force C++20 for all targets, especially problematic ones
        config.build_settings['GCC_C_LANGUAGE_STANDARD'] = 'gnu11'
        config.build_settings['CLANG_CXX_LIBRARY'] = 'libc++'

        # Remove any conflicting C++ standard flags
        config.build_settings.delete('CLANG_CXX_LANGUAGE_STANDARD_OVERRIDE')
      end
    end

    # Specifically target RCT-Folly and other React Native core pods
    installer.pods_project.targets.each do |target|
      if target.name.include?('Folly') || target.name.include?('React-') || target.name.include?('RCT')
        target.build_configurations.each do |config|
          config.build_settings['CLANG_CXX_LANGUAGE_STANDARD'] = 'c++20'
        end
      end
    end

    # Embed SPM frameworks from QuickCrypto into the app bundle
    # SPM frameworks added to Pods project need manual embedding
    main_project_path = File.join(installer.sandbox.root.parent, 'QuickCryptoExample.xcodeproj')
    main_project = Xcodeproj::Project.open(main_project_path)
    app_target = main_project.targets.find { |t| t.name == 'QuickCryptoExample' }

    if app_target
      embed_phase_name = 'Embed SPM Frameworks (QuickCrypto)'
      existing_phase = app_target.shell_script_build_phases.find { |p| p.name == embed_phase_name }

      unless existing_phase
        phase = app_target.new_shell_script_build_phase(embed_phase_name)
        phase.shell_script = <<~SCRIPT
          # Embed OpenSSL.framework from SPM build into app bundle
          # SPM builds the framework to BUILT_PRODUCTS_DIR but doesn't embed it
          OPENSSL_FRAMEWORK="${BUILT_PRODUCTS_DIR}/OpenSSL.framework"

          if [ -d "$OPENSSL_FRAMEWORK" ]; then
            echo "Found OpenSSL.framework at $OPENSSL_FRAMEWORK"
            rsync -av --delete "$OPENSSL_FRAMEWORK" "${BUILT_PRODUCTS_DIR}/${FRAMEWORKS_FOLDER_PATH}/"

            if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" ] && [ "${CODE_SIGNING_REQUIRED:-}" != "NO" ]; then
              /usr/bin/codesign --force --sign "${EXPANDED_CODE_SIGN_IDENTITY}" --preserve-metadata=identifier,entitlements "${BUILT_PRODUCTS_DIR}/${FRAMEWORKS_FOLDER_PATH}/OpenSSL.framework"
            fi
            echo "OpenSSL.framework embedded successfully"
          else
            echo "warning: OpenSSL.framework not found at $OPENSSL_FRAMEWORK"
          fi
        SCRIPT

        # Move it before the existing embed frameworks phase
        embed_pods_phase = app_target.shell_script_build_phases.find { |p| p.name == '[CP] Embed Pods Frameworks' }
        if embed_pods_phase
          app_target.build_phases.move(phase, app_target.build_phases.index(embed_pods_phase))
        end

        main_project.save
        Pod::UI.puts "[QuickCrypto] Added 'Embed SPM Frameworks (QuickCrypto)' build phase"
      end
    end
  end
end
